package org.vectrics.user.client;


import java.util.HashSet;
import java.util.Iterator;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.vectrics.VectricsException;
import org.vectrics.user.*;
import org.apache.log4j.Logger;
import org.vectrics.swing.TablePanel;
import org.vectrics.swing.Row;
import org.vectrics.swing.Cell;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.*;
import javax.swing.JTextField;
import org.vectrics.swing.GuiManager;
import org.vectrics.client.framework.ErrorFrame;
import org.vectrics.client.module.*;
import org.vectrics.location.*;

import java.awt.event.*;


/*
   ------------------------------------------------------------------------------------
   |----------------------------------------------------------------------------------|
   ||fieldHolderPanel                                                                 |
   || -------------------------------------- ---------------------------------------  |
   || | commonFieldsPanel                  | | rolesPanel                          |  |
   || |  --------------------------------  | |                                     |  |
   || |  | basicInfoPanel               |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  --------------------------------  | |                                     |  |
   || |  --------------------------------  | |                                     |  |
   || |  | homeAddressPanel             |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  --------------------------------  | |                                     |  |
   || |  --------------------------------  | |                                     |  |
   || |  | workAddressPanel             |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  |                              |  | |                                     |  |
   || |  --------------------------------  | |                                     |  |
   || |                                    | |                                     |  |
   || |                                    | |                                     |  |
   || |                                    | |                                     |  |
   || |                                    | |                                     |  |
   || |                                    | |                                     |  |
   || -------------------------------------- ---------------------------------------  |
   |----------------------------------------------------------------------------------|
   |----------------------------------------------------------------------------------|
   ||buttonPanel                                                                 |
   |----------------------------------------------------------------------------------|
   ------------------------------------------------------------------------------------


*/
public class UserEditPanel extends ModulePanel {
	
	public static String GENDER_NOT_GIVEN = "Not Given";
	public static String GENDER_MALE = "Male";
	public static String GENDER_FEMALE = "Female";
	
	public static String MARITAL_NOT_GIVEN = "Not Given";
	public static String MARITAL_MARRIED = "Married";
	public static String MARITAL_DIVORCED = "Married";
	public static String MARITAL_SINGLE = "Single";
	
	private transient Logger log = Logger.getLogger(UserEditPanel.class);
	private JPanel commonFieldsPanel = new JPanel();
	private HashSet editList = new HashSet();
	private PersonSynch personSynch = null;
	private JPanel rolesPanel = new JPanel();
	
	private JTextField userNameEdit = null;
	private JTextField firstNameEdit = null;
	private JTextField lastNameEdit = null;
	private JTextField middleNameEdit = null;
	private JTextField eMailEdit = null;
	private JTextField eMail2Edit = null;
	private JTextField homePhoneEdit = null;
	private JTextField workPhoneEdit = null;
	private JTextField cellPhoneEdit = null;
	private JTextField prefixEdit = null;
	private JTextField knownAsEdit = null;

	private JTextField homeAddress1Edit = null;
	private JTextField homeAddress2Edit = null;
	private JTextField homeCityEdit = null;
	private JTextField homeStateEdit = null;
	private JTextField homePostalCodeEdit = null;
	private JTextField homeCountryEdit = null;

	private JTextField workAddress1Edit = null;
	private JTextField workAddress2Edit = null;
	private JTextField workCityEdit = null;
	private JTextField workStateEdit = null;
	private JTextField workPostalCodeEdit = null;
	private JTextField workCountryEdit = null;

	private JCheckBox recruitRoleCheckBox = null;
	private JCheckBox employeeRoleCheckBox = null;
	private JCheckBox mgrRoleCheckBox = null;
	private JCheckBox adminRoleCheckBox = null;
	private JCheckBox candidateRoleCheckBox = null;

	private JPanel groupPanel = null;


	private JComboBox genderCombo = null;
	private JComboBox maritalStatusCombo = null;
	private JTabbedPane detailTabbedPane = null;
	
	/**
	 * Constructor 
	 */
	public UserEditPanel() {
		super();
		this.setMinimumSize(new Dimension(100, 100));
		detailTabbedPane = GuiManager.getInstance().createTabbedPane();
		
		this.setLayout(new BorderLayout());
		this.setBackground(Color.green);
		
		JPanel topPanel = new JPanel();
		topPanel.setMinimumSize(new Dimension(200, 150));
		JLabel topLabel = new JLabel();
		topLabel.setFont(GuiManager.getInstance().getStandardFont());
		topLabel.setText("User Maintenance");
		topPanel.add(topLabel);
		topPanel.setBorder(GuiManager.getInstance().getEtchedBorder()); 
		this.add(topPanel, BorderLayout.NORTH);


		JPanel fieldHolderPanel = new JPanel();
		fieldHolderPanel.setLayout(new BorderLayout());
		fieldHolderPanel.add(this.detailTabbedPane);
		createCommonFields();

		
		rolesPanel.setMinimumSize(new Dimension(200, 100));
		rolesPanel.setLayout(new BoxLayout(rolesPanel, BoxLayout.X_AXIS));
		JLabel roleLabel = new JLabel();
		rolesPanel.add(roleLabel);		
		
		TablePanel radioPanel = new TablePanel();
		radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
		recruitRoleCheckBox = makeRoleCheckBox(radioPanel, "Recruiter");
		employeeRoleCheckBox = makeRoleCheckBox(radioPanel, "Employee");
		mgrRoleCheckBox = makeRoleCheckBox(radioPanel, "Hiring Manager");
		adminRoleCheckBox = makeRoleCheckBox(radioPanel, "Administrator");
		candidateRoleCheckBox = makeRoleCheckBox(radioPanel, "Candidate");
		rolesPanel.add(radioPanel);		
		rolesPanel.setBorder(
						BorderFactory.createCompoundBorder(
										BorderFactory.createTitledBorder("Roles"),
										BorderFactory.createEmptyBorder(5,5,5,5)));

		this.add(fieldHolderPanel, BorderLayout.CENTER);
		this.add(createButtonsPanel(), BorderLayout.SOUTH);
		this.repaint();
		log.info("constructor() - end - userNameEdit.text = " + userNameEdit.getText());
	}

	
	private JCheckBox makeRoleCheckBox(JPanel radioPanel, String label) {
		JCheckBox checkBox = new JCheckBox();
		checkBox.setText(label);
		checkBox.setFont(GuiManager.getInstance().getStandardFont());
		radioPanel.add(checkBox);
		return(checkBox);
	}
	

	private void clearRoleCheckBoxes() {
		recruitRoleCheckBox.setSelected(false);
		employeeRoleCheckBox.setSelected(false);
		mgrRoleCheckBox.setSelected(false);
		adminRoleCheckBox.setSelected(false);
		candidateRoleCheckBox.setSelected(false);
	}

	private void setRoleEntry(Person user) {
		clearRoleCheckBoxes();
		Iterator iter = user.getPrivileges().iterator();
		while (iter.hasNext()) {
			UserPrivilege userPrivilege = (UserPrivilege)iter.next();
			String role = userPrivilege.getPrivilegeType().getCode();
			if (role.indexOf("recruiter") >= 0)
				recruitRoleCheckBox.setSelected(true); 			
			if (role.indexOf("employ") >= 0)
				employeeRoleCheckBox.setSelected(true); 			
			if (role.indexOf("mgr") >= 0)
				mgrRoleCheckBox.setSelected(true); 			
			if (role.indexOf("admin") >= 0)
				adminRoleCheckBox.setSelected(true); 			
			if (role.indexOf("cand") >= 0)
				candidateRoleCheckBox.setSelected(true); 			
		}
	}			
	
	
	public void setUser(PersonSynch personSynch) {
		this.personSynch = personSynch;
		clearControls();
		if (personSynch != null) {
			Person user = personSynch.getPerson();
			userNameEdit.setText(user.getUser().getUserName());
			
			log.info("setUser() - userNameEdit.text = " + userNameEdit.getText());
			firstNameEdit.setText(user.getFirstName());
			lastNameEdit.setText(user.getLastName());
			middleNameEdit.setText(user.getMiddleName());
			prefixEdit.setText(user.getNamePrefix());
			knownAsEdit.setText(user.getKnownAs());
			
			genderCombo.setSelectedItem(Gender.find(user.getGender()));

			
			maritalStatusCombo.setSelectedItem(UserEditPanel.MARITAL_NOT_GIVEN);
			if (user.getMaritalStatus() != null) {
				if (user.getMaritalStatus().toLowerCase().startsWith("m")) {
					maritalStatusCombo.setSelectedItem(UserEditPanel.MARITAL_MARRIED);
				}
				else if (user.getMaritalStatus().toLowerCase().startsWith("s")) {
					maritalStatusCombo.setSelectedItem(UserEditPanel.MARITAL_SINGLE);
				}
				else if (user.getMaritalStatus().toLowerCase().startsWith("d")) {
					maritalStatusCombo.setSelectedItem(UserEditPanel.MARITAL_DIVORCED);
				}
			}
            
			setRoleEntry(user);			
			ContactInfo contactInfo = user.getContactInfo(); 
			if (user.getContactInfo() != null) {			
				eMailEdit.setText(contactInfo.getEmail());
				eMail2Edit.setText(contactInfo.getEmail2());
				if (contactInfo.getHomePhone() != null)
					homePhoneEdit.setText(contactInfo.getHomePhone().getFormattedNumber());
				if (contactInfo.getWorkPhone() != null)
					workPhoneEdit.setText(contactInfo.getWorkPhone().getFormattedNumber());
				if (contactInfo.getCellPhone() != null)
					cellPhoneEdit.setText(contactInfo.getCellPhone().getFormattedNumber());
				
				Address homeAddress = user.getContactInfo().getHomeAddress();
				if (homeAddress != null) {
					homeAddress1Edit.setText(homeAddress.getAddress1());
					homeAddress2Edit.setText(homeAddress.getAddress2());
					homeCityEdit.setText(homeAddress.getCity());
					homeStateEdit.setText(homeAddress.getState());
					homeCountryEdit.setText(homeAddress.getCountryCode());
					homePostalCodeEdit.setText(homeAddress.getPostalCode());
				}
				
				Address workAddress = user.getContactInfo().getWorkAddress();
				if (workAddress != null) {
					workAddress1Edit.setText(workAddress.getAddress1());
					workAddress2Edit.setText(workAddress.getAddress2());
					workCityEdit.setText(workAddress.getCity());
					workStateEdit.setText(workAddress.getState());
					workCountryEdit.setText(workAddress.getCountryCode());
					workPostalCodeEdit.setText(workAddress.getPostalCode());
				}
			}
		} 
		log.info("setUser() - end - userNameEdit.text = " + userNameEdit.getText());
		
	}
	
	
	protected void clearControls() {
		log.info("clearControls() - userNameEdit.text = " + userNameEdit.getText());
		clearEdits();
	}
	
	protected void clearEdits() {
		Iterator iter = editList.iterator();
		while (iter.hasNext()) {
			JTextField edit = (JTextField)iter.next();
			edit.setText("");	
		}
	}
	
	private JPanel createButtonsPanel() {
		log.info("createButtonsPanel() - method to display buttons for form");
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout());
		JButton saveButton = GuiManager.getInstance().createButton("Save", 90, 20);
		saveButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					saveButtonPressed(e);
				}
			});
		panel.add(saveButton);
		
		
		JButton cancelButton = GuiManager.getInstance().createButton("Cancel", 90, 20);
		cancelButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					cancelButtonPressed(e);
				}
			});
		
		panel.add(cancelButton);
		panel.setMaximumSize(new Dimension(4000, 30));
		panel.setBorder(GuiManager.getInstance().getEtchedBorder());
		return(panel);
	}
	
	private JTextField createEdit() {
		JTextField edit = new JTextField();
		edit.setFont(GuiManager.getInstance().getStandardFont());
		//edit.setMaximumSize(new Dimension(200, 22));
		//edit.setMinimumSize(new Dimension(10, 22));
		//edit.setPreferredSize(new Dimension(100, 22));
		editList.add(edit);
		return(edit);
	}

	protected JTextField addEditField(TablePanel table, String label) {
		JTextField editBox = createEdit();
		addField(table, label, editBox);
		return(editBox);
	}
	
	
	private JComboBox makeGenderCombo() {
		genderCombo = new JComboBox();
		genderCombo.setFont(GuiManager.getInstance().getStandardFont());
		Iterator iter = Gender.findAll().iterator();
		while (iter.hasNext()) {
			genderCombo.addItem(iter.next());
		}
		
		return(genderCombo);		
	}

	private JComboBox makeMaritalStatusCombo() {
		maritalStatusCombo = new JComboBox();
		maritalStatusCombo.setFont(GuiManager.getInstance().getStandardFont());
		maritalStatusCombo.addItem(MARITAL_NOT_GIVEN);
		maritalStatusCombo.addItem(MARITAL_MARRIED);
		maritalStatusCombo.addItem(MARITAL_SINGLE);
		maritalStatusCombo.addItem(MARITAL_DIVORCED);
		
		return(maritalStatusCombo);		
	}

	public void createCommonFields() {
		log.info("createCommonFields() - method to provide edit controls for common user properties");
				
		TablePanel basicInfoTable = makeSection("Basic Information");
		userNameEdit = addEditField(basicInfoTable, "User Name");
		firstNameEdit = addEditField(basicInfoTable, "First Name");
		middleNameEdit = addEditField(basicInfoTable, "Middle Name");
		lastNameEdit = addEditField(basicInfoTable, "Last Name");
		prefixEdit = addEditField(basicInfoTable, "Prefix");
		knownAsEdit = addEditField(basicInfoTable, "Known As");
		eMailEdit = addEditField(basicInfoTable, "E-Mail 1");
		eMail2Edit = addEditField(basicInfoTable, "E-Mail 2");
		addField(basicInfoTable, "Gender", makeGenderCombo());
		addField(basicInfoTable, "Marital Status", makeMaritalStatusCombo());
		homePhoneEdit = addEditField(basicInfoTable, "Home Phone");
		workPhoneEdit = addEditField(basicInfoTable, "Work Phone");
		cellPhoneEdit = addEditField(basicInfoTable, "Cell Phone");
		
		TablePanel homeAddrPanel = makeSection("Home Address");
		homeAddress1Edit = addEditField(homeAddrPanel, "Address 1");
		homeAddress2Edit = addEditField(homeAddrPanel, "Address 2");
		homeCityEdit = addEditField(homeAddrPanel, "City");
		homeStateEdit = addEditField(homeAddrPanel, "State");
		homeCountryEdit = addEditField(homeAddrPanel, "Country");
		homePostalCodeEdit = addEditField(homeAddrPanel, "Postal Code");
		
		
		TablePanel workAddrPanel =  makeSection("Work Address");
		workAddress1Edit = addEditField(workAddrPanel, "Address 1");
		workAddress2Edit = addEditField(workAddrPanel, "Address 2");
		workCityEdit = addEditField(workAddrPanel, "City");
		workStateEdit = addEditField(workAddrPanel, "State");
		workCountryEdit = addEditField(workAddrPanel, "Country");
		workPostalCodeEdit = addEditField(workAddrPanel, "Postal Code");
	}


	private TablePanel makeSection(String label) {
		TablePanel tablePanel = new TablePanel();
		detailTabbedPane.addTab(label, tablePanel);
		
		//groupPanel.setBorder(BorderFactory.createCompoundBorder(
		//					BorderFactory.createTitledBorder(label),
		//					BorderFactory.createEmptyBorder(5,5,5,5)));
		return(tablePanel);
	}


	private void addField(TablePanel table, String labelText, JComponent editComponent) {
		JLabel label = new JLabel();
		label.setText(labelText);
		label.setFont(GuiManager.getInstance().getStandardFont());
		label.setMinimumSize(new Dimension(50, 22));
		label.setMaximumSize(new Dimension(150, 22));
		Row panelRow = table.addRow();

		Cell cell = panelRow.addCell(label);
		cell = panelRow.addCell(editComponent);
	}


	private void save() throws VectricsException {
		if (personSynch != null) {
			Person user = personSynch.getPerson();
			user.createUserIfNotExist().setUserName(userNameEdit.getText());
			log.info("save() - UserNameEdit.text = " + userNameEdit.getText());
			log.info("save() - lastNameEdit.text = " + lastNameEdit.getText());
			user.setLastName(lastNameEdit.getText());
			user.setFirstName(firstNameEdit.getText());
			user.setMiddleName(middleNameEdit.getText());
			user.setNamePrefix(prefixEdit.getText());
			user.setKnownAs(knownAsEdit.getText());
			user.setGender(((Gender)genderCombo.getSelectedItem()).getCode());
				
			if (maritalStatusCombo.getSelectedItem().equals(UserEditPanel.MARITAL_MARRIED)) {
				user.setMaritalStatus(User.MARITAL_STATUS_MARRIED);				
			}
			else if (maritalStatusCombo.getSelectedItem().equals(UserEditPanel.MARITAL_DIVORCED)) {
				user.setMaritalStatus(User.MARITAL_STATUS_DIVORCED);				
			}
			else if (maritalStatusCombo.getSelectedItem().equals(UserEditPanel.MARITAL_SINGLE)) {
				user.setMaritalStatus(User.MARITAL_STATUS_SINGLE);				
			}
			else {
				user.setMaritalStatus(User.MARITAL_STATUS_NOT_GIVEN);				
			}

			user.clearPrivileges();
			if (this.adminRoleCheckBox.isSelected()) {
//				user.addRole("recruit-admin", null);
			}
			if (this.candidateRoleCheckBox.isSelected()) {
	//			user.addRole("recruit-candidate", null);
			}
			if (this.mgrRoleCheckBox.isSelected()) {
		//		user.addRole("recruit-mgr", null);
			}
			if (this.employeeRoleCheckBox.isSelected()) {
//				user.addRole("recruit-employee", null);
			}
			if (this.recruitRoleCheckBox.isSelected()) {
//				user.addRole("recruit-recruiter", null);
			}
			            
			ContactInfo contactInfo = user.createContactInfoIfNotExist(); 
			contactInfo.setHomePhone(new PhoneNumber(homePhoneEdit.getText()));
			contactInfo.setWorkPhone(new PhoneNumber(workPhoneEdit.getText()));
			contactInfo.setCellPhone(new PhoneNumber(cellPhoneEdit.getText()));
			contactInfo.setEmail(eMailEdit.getText());
			contactInfo.setEmail2(eMail2Edit.getText());

			
			Address homeAddress = contactInfo.getHomeAddress();
			if (homeAddress == null)
				homeAddress = new Address();
			homeAddress.setAddress1(homeAddress1Edit.getText());
			homeAddress.setAddress2(homeAddress2Edit.getText());
	/*		homeAddress.setCity(homeCityEdit.getText());
			homeAddress.setState(homeStateEdit.getText());
			homeAddress.setPostalCode(homePostalCodeEdit.getText());
			homeAddress.setCountryCode(homeCountryEdit.getText());*/
			
			Address workAddress = contactInfo.getWorkAddress();
			if (workAddress == null)
				workAddress = new Address();
			workAddress.setAddress1(workAddress1Edit.getText());
			workAddress.setAddress2(workAddress2Edit.getText());
		/*	workAddress.setCity(workCityEdit.getText());
			workAddress.setState(workStateEdit.getText());
			workAddress.setPostalCode(workPostalCodeEdit.getText());
			workAddress.setCountryCode(workCountryEdit.getText());*/
			
			
			UserDataManager.getInstance().updateUser(personSynch);			
		} 
	}



	protected void saveButtonPressed(ActionEvent e) {
		try {
			save();
		}
		catch (Exception ex) {
			ErrorFrame.showError("Error during Save", "Error saving user.", "Exception: " + ex.getMessage());
		}
		leave();
	}

	protected void cancelButtonPressed(ActionEvent e) {
		leave();
	}

	private void leave() {
		try {
			this.showPreviousModule();
		}
		catch (VectricsException ue) {
			log.error("UnknownModuleException while trying to show previous module");
		}
	}


}
